'''
Author: StormAX 724456475@qq.com
Date: 2024-03-22 20:22:32
LastEditors: StormAX 724456475@qq.com
LastEditTime: 2024-03-23 21:22:35
FilePath: \debug_client\msg_loop.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from PySide2.QtCore import QObject
import json
import zmq
from data_serve.client import *

class Worker(QObject):
    # finished = Signal()

    def __init__(self, ip, callback):
        super().__init__()
        self.ip = ip
        self.is_running = True
        self.callback = callback
            
    def do_work(self):
        context = zmq.Context()
        socket = context.socket(zmq.SUB)
        socket.setsockopt_string(zmq.SUBSCRIBE, '')
        socket.connect(f"tcp://{self.ip}:9776")
        print(f"connected {self.ip}")
        received_chunks = []
        poller = zmq.Poller()
        poller.register(socket, zmq.POLLIN)
        i=0
        while self.is_running:
            # print("listening...")
            socks = dict(poller.poll(timeout=1000))  # 设置超时时间为1秒
            if socket in socks and socks[socket] == zmq.POLLIN:
                chunk = socket.recv_string()
                if len(chunk) == 0: continue
                received_chunks.append(chunk)
                if not socket.getsockopt(zmq.RCVMORE):
                    assembled_message = ''.join(received_chunks).replace("[debug]", "", 1)
                    json_obj = json.loads(assembled_message)
                    debug_id = json_obj["debug_id"]
                    process = json_obj["PROCESS"]
                    # with open(f"log/{debug_id}.json", "a") as f:
                    json_obj = format_json(json_obj)
                    self.callback((debug_id , process, json_obj))
                        # json_str = json.dumps(json_obj)
                        # f.write(json_str + '\n')
                    received_chunks.clear()
                    i += 1

    def stop(self):
        self.is_running = False
